package easy.二进制求和;

import java.util.Arrays;

public class Solution {
    public String addBinary(String a, String b) {
        int lengthA = a.length();
        int lengthB = b.length();
        int carry = 0;//两字符相加后的结果
        StringBuffer buffer = new StringBuffer();//用来记录计算后的字符串
        for (int i = 0; i < Math.max(lengthA, lengthB); i++) {
            //'1'的Unicode的值是49，'0'的Unicode的值是48，字符转数字
            carry += i < lengthA ? a.charAt(lengthA - 1 - i) - '0' : 0;
            carry += i < lengthB ? b.charAt(lengthB - 1 - i) - '0' : 0;
            buffer.append((char) (carry % 2 + '0'));//对2求余取剩下的值,再转字符
            carry /= 2;//进位
        }
        if (carry == 1) {
            buffer.append('1');//加上最前面的进位
        }
        buffer.reverse();//反转
        return buffer.toString();
    }

    public static void main(String[] args) {
        String a = "111", b = "1";
        String a2 = "1010", b2 = "1011";
        String a3 = "101011", b3 = "1011011101";
        Solution solution = new Solution();
        System.out.println(solution.addBinary(a, b));
        System.out.println(solution.addBinary(a2, b2));
        System.out.println(solution.addBinary(a3, b3));
    }
}
